package com.ojoin.ojoin.eb_spider.service.catchdata;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.BankCardCheck;
import com.ojoin.ojoin.eb_spider.service.impl.SLDataCatchBaseServiceImpl;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.NumberUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.WaitUtil;
import com.ojoin.trade.common.utils.excel.ExcelReaderUtil;
import com.ojoin.trade.common.utils.excel.IRowReader;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;

/**
 * @author Administrator url-->
 *         http://order.shop.jd.com/order/sSopUp_newYiShipList.action 1.
 * 
 * 
 */

@Service
public class ThirdSellerTMALLDataCatchServiceImpl extends
		SLDataCatchBaseServiceImpl {

	private Logger log = LoggerFactory
			.getLogger(ThirdSellerTMALLDataCatchServiceImpl.class);

	private static final String logIn_taobao = "https://mai.taobao.com/seller_admin.htm";

	private long allAmount = 0;

	@Override
	public boolean LoginByUserInfo(String baseUrl, String username,
			String password) throws Exception {

		this.getWebDriver()
				.get("https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fmyseller.taobao.com%2Fseller_admin.htm");

		if (this.getWebDriver().IsDisplayed("id", "J_Quick2Static")) {
			this.getWebDriver().click("id", "J_Quick2Static");
		}

		this.getWebDriver().sendKeys("id", "TPL_username_1", username);
		this.getWebDriver().sendKeys("id", "TPL_password_1", password);

		WaitUtil.waitTimeSeconds(60);

		this.getWebDriver().click("id", "J_SubmitStatic");

		return this.getWebDriver().isLogin(logIn_taobao);
	}

	@Override
	public String catchSupplierName() throws BusinessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BankCardCheck catchSupplierAccount() throws BusinessException {
		// TODO Auto-generated method stub
		 BankCardCheck bcc = new BankCardCheck();
		 
		return null;
	}

	public static void main(String[] args) {
		String str = "成交时间：2016-04-15 07:13:34 到 2016-07-14 07:13:34";
		Pattern pattern = Pattern.compile("[:,：]\\s*(.{10}).*到\\s*(.{10})");
		Matcher matcher = pattern.matcher(str);
		if (matcher.find()) {
			String time = matcher.group(1);
		}

	}

	public boolean dowanLoad() throws Exception {

		String url = "https://trade.taobao.com/trade/itemlist/list_export_order.htm?page_no=1";
		this.getWebDriver().get(url);

		List<WebElement> lis = this.getWebDriver().findElements("css",
				"#batch-export-wrapper > div.sheet-list-container > ul  li ");

		if (!CommonUtils.isEmpty(lis)) {
			Iterator<WebElement> it = lis.iterator();
			while (it.hasNext()) {
				WebElement li = it.next();
				// 报表申请时间： 2016-07-14 07:13:34
				String downtime = this.getWebDriver().getText(li, "css", "h2");
				Pattern pattern = Pattern.compile("[:,：]\\s*(.{10})");

				if (!CommonUtils.isEmpty(downtime)) {
					Matcher matcher = pattern.matcher(downtime);
					if (matcher.find()) {
						downtime = matcher.group(1);
					}

				} else {
					continue;
				}

				if (TimeUtils.getCurDate().equals(downtime)) {
					// 成交时间：2016-04-15 07:13:34 到 2016-07-14 07:13:34

					String time = this.getWebDriver().getText(li, "css",
							"table > caption");

					pattern = Pattern.compile("[:,：]\\s*(.{10}).*到\\s*(.{10})");
					Matcher matcher = pattern.matcher(time);
					if (matcher.find()) {
						String stime = matcher.group(1);
						String etime = matcher.group(2);
						if (TimeUtils.getCurDate().equals(etime)
								&& TimeUtils.getDateSpaceOfDay(stime, etime) > 30) {

							this.getWebDriver().click(li, "css",
									" div > a:nth-child(1)");

							return true;
						}
					}
				}

			}
		}

		return false;
	}

	@Override
	public boolean getUnpayAccountData() throws BusinessException, IOException {
		try {
			if (!dowanLoad()) {
				this.getWebDriver()
						.get("https://trade.taobao.com/trade/itemlist/list_sold_items.htm?action=itemlist/SoldQueryAction&event_submit_do_query=1&auctionStatus=SEND&tabCode=haveSendGoods");

				String stime = TimeUtils.getDateBefore(20) + " 0:00:00";

				String etime = TimeUtils.getCurDate() + " 0:00:00";

				this.getWebDriver()
						.sendKeys(
								"css",
								"#sold_container > div > div:nth-child(1) > div:nth-child(1) > form > div:nth-child(1) > div:nth-child(2) > div > div > input:nth-child(1)",
								stime);

				this.getWebDriver()
						.sendKeys(
								"css",
								"#sold_container > div > div:nth-child(1) > div:nth-child(1) > form > div:nth-child(1) > div:nth-child(2) > div > div > input:nth-child(3)",
								etime);

				this.getWebDriver().click("id", "bizOrderId");
				this.getWebDriver()
						.click("css",
								"#sold_container > div > div:nth-child(1) > div:nth-child(1) > form > div:nth-child(8) > div > div > button.button-mod__button___Ww52F.button-mod__default___31VoJ");

				this.getWebDriver()
						.click("css",
								"#sold_container > div > div:nth-child(1) > div:nth-child(1) > div > div > button:nth-child(1)");

				boolean flag = true;

				int count = 0;

				while (flag) {
					count++;
					WaitUtil.waitTimeSeconds(20);
					LogUtils.info(log, "wiat time  %s", 20 * count);

					if (this.getWebDriver()
							.isLogin(
									"https://trade.taobao.com/trade/itemlist/list_export_order.htm?page_no=1")) {

						boolean isExit = this
								.getWebDriver()
								.IsExist(
										"css",
										"#batch-export-wrapper > div.sheet-list-container > ul > li:nth-child(1) > div > p");

						if (!isExit) {
							flag = !dowanLoad();
						}

					} else {
						throw new BusinessException("下载文件出错");
					}

				}

				LogUtils.info(log, "download success ,time is [%s]", 20 * count);
			}

			dealExcel();

		} catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("获取未结算单据出错");

		}

		return true;
	}

	public Long dealExcel() throws Exception {
		final List<TbSlSupplyPayment> payments = new ArrayList<TbSlSupplyPayment>();
		// final Set<String> set = new HashSet<String>();
		allAmount = 0;
		File downloadFileDir = new File(this.getAssistCatchData().getDownloadDir());

		IRowReader reader = new IRowReader() {

			public void getRows(int sheetIndex, String sheetName, int curRow,
					List<String> rowlist) {

				if (0 == curRow) {
					return;
				}

				String stramount = rowlist.get(8).replaceAll("\"", "");

				String time = rowlist.get(17).replaceAll("\"", "");
				time = time.substring(0, 10).replace(" ", "");

				try {
					long m = TimeUtils.getDateSpaceOfDay(
							TimeUtils.getDateBefore(20), time);
					if (m >= 0) {
						allAmount += NumberUtils.getLongAmount(stramount);
					}
				} catch (Exception e) {
					LogUtils.error(log, e);
				}

			}
		};

		FileInputStream in = null;
		File files = null;
		try {
			files = DownloadUtils.waitFileDownloadOver(downloadFileDir,
					"^ExportOrderList.*.csv$");

			LogUtils.info(log, "文件名为：" + files.getAbsolutePath() + "-->文件大小："
					+ files.length() / 1024 + "kb");

			in = new FileInputStream(files);

			ExcelReaderUtil.readCSV(reader, in, "GBK");

			files.renameTo(new File(files.getParent() + File.separator
					+ UUID.randomUUID().toString() + ".csv"));

			TbSlSupplyPayment payment = new TbSlSupplyPayment();

			payment.setPlatformAccountId(this.getAssistCatchData().getStartMess().getPlatformUser()
					.getId());
			payment.setSettlementId(TimeUtils.getCurDate());

			payment.setSettlementState(TbSlSupplyPayment.CHECKEDPAY);

			payment.setCreateDate(TimeUtils.getCurDate());
			payment.setSettlementDate(TimeUtils.getCurDate());

			payment.setAmount(allAmount);
			payments.add(payment);

			this.getAssistCatchData().getCata().setSettlement(payments);

			LogUtils.info(log,
					"getUnpayAccountData--payments：" + payments.size()
							+ "-->执行完毕");

		} catch (Exception e) {
			LogUtils.error(log, e);
			throw new BusinessException("解析payment文件失败");
		} finally {
			IOUtils.closeQuietly(in);
		}

		return allAmount;
	}

	@Override
	public boolean getPayAccountData() throws BusinessException, Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean getOutstoreOrderData() throws IOException {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean getInstoreOrderData() throws IOException, Exception {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	public BankCardCheck isSupplyAccountCorrect() throws BusinessException {
		BankCardCheck bcc = new BankCardCheck();
		bcc.setCorrect(true);
		
		return bcc;
	}
}
